using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Transforms;

namespace HelloCube.Reparenting
{
    public partial struct ReparentingSystem : ISystem
    {
        const float mInterval = 1.25f;
        bool mAttached;
        float mTimer;

        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            mTimer = mInterval;
            mAttached = false;
            state.RequireForUpdate<Execute.Reparenting>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            mTimer -= SystemAPI.Time.DeltaTime;
            if (mTimer > 0) return;
            mTimer = mInterval;

            var rotatorEntity = SystemAPI.GetSingletonEntity<RotateSpeed>();
            var ecb = new EntityCommandBuffer(Allocator.Temp);

            if (mAttached)
            {
                //将 rotatorEntity 的子物体与其分离（Transform 层面上的）
                DynamicBuffer<Child> children = SystemAPI.GetBuffer<Child>(rotatorEntity);
                for (int i = 0; i < children.Length; i++)
                {
                    //使用ecb, 否则 RemoveComponent 操作会使 DynamicBuffer 失效
                    ecb.RemoveComponent<Parent>(children[i].Value);
                }
            }
            else
            {
                //检索有 Transform 但没有 RotateSpeed 组件的实体
                foreach (var (transform, entity) in SystemAPI.Query<RefRO<LocalTransform>>().WithNone<RotateSpeed>()
                             .WithEntityAccess())
                {
                    //与 rotatorEntity 建立父子联系（Transform 层面上的）
                    ecb.AddComponent(entity, new Parent()
                    {
                        Value = rotatorEntity,
                    });
                }
            }

            ecb.Playback(state.EntityManager); //执行 ecb
            mAttached = !mAttached;
        }
    }
}